package com.weijing.pretty_app.util

import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Build
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.widget.AppCompatImageView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

object CoreUtil {

    /**
     * dp转px
     */
    fun dp2px(context: Context, dpValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }

    /**
     * 禁止 EditText 弹出系统键盘
     */
    fun disableSystemKeyboard(editText: EditText) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            editText.showSoftInputOnFocus = false
        } else {
            try {
                val method = EditText::class.java.getMethod(
                    "setShowSoftInputOnFocus", Boolean::class.javaPrimitiveType
                )
                method.isAccessible = true
                method.invoke(editText, false)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    /**
     * tv布局2秒倒计时就隐藏
     */
    fun showTvCustomToast(view: TextView, durationMillis: Long = 2000L) {
        view.visibility = View.VISIBLE

        CoroutineScope(Dispatchers.Main).launch {
            delay(durationMillis)
            view.visibility = View.INVISIBLE
        }
    }

    /**
     * 布局倒计时就隐藏
     */
    fun showIvCustomToast(
        view: AppCompatImageView, targetResourceId: Int,
        resourceId: Int, durationMillis: Long = 2000L
    ) {
        view.setImageResource(targetResourceId)

        CoroutineScope(Dispatchers.Main).launch {
            delay(durationMillis)
            view.setImageResource(resourceId)
        }
    }

    //获取版本号versionName
    private fun getPackageInfo(context: Context): PackageInfo {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            context.packageManager.getPackageInfo(
                context.packageName,
                PackageManager.PackageInfoFlags.of(0)
            )
        } else {
            context.packageManager.getPackageInfo(context.packageName, 0)
        }
    }

    //获取版本号versionName
    fun getVersionName(context: Context): String {
        return getPackageInfo(context).versionName
    }

    //获取年月日
    fun getCurrentDateWithSimpleDateFormat(): String {
        val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        return sdf.format(Date())
    }

    //下载apk
    fun downLoadFileWithProgress(
        fileUrl: String, savePath: String, fileName: String,
        listener: ProgressResponseBody.ProgressListener
    ) {
        val client = OkHttpClient.Builder()
            .addNetworkInterceptor {
                val response = it.proceed(it.request())
                //换成ProgressResponseBody
                response.newBuilder()
                    .body(ProgressResponseBody(response.body, listener))
                    .build()
            }
            .build()

        val request = Request.Builder()
            .url(fileUrl)
            .build()
        val call = client.newCall(request)
        listener.newCall(call)
        call.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
            }

            override fun onResponse(call: Call, response: Response) {
                if (response.code != 200) {
                    /**
                     * 失败回调监听
                     */
                    listener.failed()
                    return
                }
                if (response.body == null) {
                    listener.failed()
                    return
                }
                //将返回结果转化为流，并写入文件
                var len: Int
                val buf = ByteArray(2048)
                val inputStream = response.body!!.byteStream()
                val dirFile = File(savePath)
                if (!dirFile.exists()) {
                    dirFile.mkdirs()
                }
                /**
                 * 写入本地文件
                 */
                val file = File(savePath + File.separatorChar + fileName)
                if (file.exists()) {
                    file.delete()
                }
                /**
                 *如果服务器没有返回的话,使用自定义的文件名字
                 */

                val fileOutputStream = FileOutputStream(file)
                len = inputStream.read(buf)
                while (len != -1) {
                    fileOutputStream.write(buf, 0, len)
                    len = inputStream.read(buf)
                }
                fileOutputStream.flush()
                fileOutputStream.close()
                inputStream.close()
                listener.success(file.absolutePath)
            }
        })
    }

    //版本对比
    fun compareVersions(localVersion: String, serverVersion: String): Int {
        val localParts = localVersion.split(".").map { it.toIntOrNull() ?: 0 }
        val serverParts = serverVersion.split(".").map { it.toIntOrNull() ?: 0 }

        // 逐级比较主版本、次版本、修订号
        for (i in 0 until maxOf(localParts.size, serverParts.size)) {
            val localPart = localParts.getOrElse(i) { 0 }
            val serverPart = serverParts.getOrElse(i) { 0 }
            when {
                serverPart > localPart -> return 1
                serverPart < localPart -> return -1
            }
        }
        return 0
    }
}